import 'package:flutter/material.dart';
import 'package:get/get.dart' hide WidgetPaddingX;
import 'package:hotpot/basic/app_colors.dart';
import 'package:hotpot/extensions/data.dart';
import 'package:hotpot/models/create_order_req.dart';
import 'package:hotpot/models/shop_detail.dart';
import 'package:hotpot/pages/table/table_page.dart';
import 'package:hotpot/widgets/styles/icon_box.dart';
import 'package:hotpot/widgets/widget_ext.dart';
import 'package:hotpot/widgets/z_container.dart';
import 'package:hotpot/widgets/z_image.dart';

class ProductDetailWidget extends StatefulWidget {
  final ShopDetailProductProducts? products;
  final CreateOrderReqLines line;
  final void Function() onAdd;
  final void Function() onClose;

  const ProductDetailWidget(this.products, this.line, this.onAdd, this.onClose, {super.key});

  @override
  State<ProductDetailWidget> createState() => _ProductDetailWidgetState();
}

class _ProductDetailWidgetState extends State<ProductDetailWidget> {
  ShopDetailProductProducts? get products => widget.products;

  List<ShopDetailAttributes> attrList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    attrList = detail.attributes!.values.map((e) => ShopDetailAttributes.fromJson(e)).toList();
  }

  @override
  Widget build(BuildContext context) {
    if (products == null) return const SizedBox();
    return Stack(
      alignment: Alignment.center,
      children: [
        // const ZContainer(
        //   height: double.infinity,
        //   color: Colors.white10,
        // ).gestureDetector(onTap: widget.onClose).positioned(left: 0, right: 0, top: 0, bottom: 0),
        ZContainer(
          // width: 344,
          // height: 400,
          // radius: 19,
          color: AppColors.baColor,
          child: Column(
            children: [
              8.hSizedBox,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  'images/img_back.png'
                      .assetImage(width: 10, height: 15)
                      .paddingOnly(left: 15, top: 0)
                      .gestureDetector(onTap: widget.onClose),
                  products!.name.text(size: 12, color: Colors.black, bold: true),
                  'images/img_back.png'.assetImage(width: 10, height: 15).paddingOnly(right: 15).opacity(0),
                ],
              ),
              13.hSizedBox,
              SingleChildScrollView(
                child: Column(
                  children: [
                    PageView(
                      onPageChanged: onPageChanged,
                      children: [
                        if (products!.image != null) imgBox(products!.image!),
                        ...products!.images?.map((e) => imgBox(e)) ?? [],
                      ],
                    ).sizedBox(width: 133, height: 133),
                    15.hSizedBox,
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ...List.generate(products!.images?.length ?? 0, imgIndexBox),
                      ],
                    ),
                    10.hSizedBox,
                    SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: [
                          ...products?.allergySource?.map((e) =>
                                  ZImage.memory(bytes: e.bytes, width: 13, height: 13, fit: BoxFit.cover)
                                      .paddingOnly(right: 5)) ??
                              [],
                        ],
                      ),
                    ),
                    16.hSizedBox,
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ZContainer(
                          margin: const EdgeInsets.only(right: 7),
                          radius: 50,
                          width: 73,
                          height: 28,
                          color: const Color(0xFFFFBC42),
                          child: Row(
                            children: [
                              7.wSizedBox,
                              const IconBox(Icons.remove, 15, 12).gestureDetector(onTap: () {
                                if (widget.line.qty! == 1) return;
                                widget.line.qty = widget.line.qty! - 1;
                                widget.line.priceSubtotal = widget.line.qty! * widget.line.priceUnit!;
                                setState(() {});
                              }),
                              widget.line.qty
                                  .text(size: 12, color: Colors.white, bold: true, textAlign: TextAlign.center)
                                  .expanded(),
                              const IconBox(Icons.add, 15, 12).gestureDetector(onTap: () {
                                widget.line.qty = widget.line.qty! + 1;
                                widget.line.priceSubtotal = widget.line.qty! * widget.line.priceUnit!;
                                setState(() {});
                              }),
                              7.wSizedBox,
                            ],
                          ),
                        ),
                      ],
                    ),
                    11.hSizedBox,
                    ZContainer(
                      alignment: Alignment.center,
                      width: 367,
                      child:
                          products!.publicDescriptionText.text(size: 9, bold: true, color: const Color(0xFFABABAB), maxLines: 99),
                    ),
                    9.hSizedBox,
                    ...products!.attributeLineIds!.map(attrGroup),
                  ],
                ),
              ).expanded(),
              8.hSizedBox,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  (products!.lstPrice.fixed != '0.00' ? products!.lstPrice.fixed : '')
                      .text(size: 20, color: Colors.black, bold: true),
                  ZContainer(
                    color: const Color(0xFF22CE67),
                    radius: 18,
                    width: 82,
                    height: 23,
                    alignment: Alignment.center,
                    child: 'ADD'.text(size: 7, bold: true, color: Colors.white),
                  ).gestureDetector(onTap: widget.onAdd),
                ],
              ).paddingOnly(bottom: 12, right: 13, left: 13),
            ],
          ),
        ),
      ],
    );
  }

  Widget attrGroup(int attrId) {
    var attrData = attrList.firstWhereOrNull((e) => attrId == e.id);
    if (attrData == null) return const SizedBox();
    item(ShopDetailAttributesValues data) {
      var select = widget.line.attributeValueIds!.contains(data.id);
      return ZContainer(
        height: 19,
        padding: const EdgeInsets.symmetric(horizontal: 10),
        radius: 50,
        // alignment: Alignment.center,
        margin: const EdgeInsets.only(right: 4, top: 4),
        color: select ? const Color(0xFF252836) : const Color(0xFFF0F5FA),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            data.name.text(color: select ? const Color(0xFF22CE67) : const Color(0xFF121223), bold: select, size: 7),
          ],
        ),
      ).gestureDetector(onTap: () {
        if (attrData.displayType == 'radio') {
          if (select) {
          } else {
            widget.line.attributeValueIds!.removeWhere((e) => attrData.values!.map((e) => e.id).contains(e));
            widget.line.attributeValueIds!.add(data.id!);
          }
        } else {
          if (select) {
            widget.line.attributeValueIds!.remove(data.id!);
            widget.line.attributeMultiValue!.remove('${data.id}');
          } else {
            var maxQty = (attrData.maxQty ?? 0) == 0 ? (attrData.values?.length ?? 0) : (attrData.maxQty ?? 0);
            if (maxQty > widget.line.attributeValueIds!.length) {
              widget.line.attributeValueIds!.add(data.id!);
              widget.line.attributeMultiValue!['${data.id}'] = 1;
            }
          }
        }
        setState(() {});
      });
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ''.text(size: 7),
        attrData.name.text(size: 7, color: const Color(0xFFA0A5BA)),
        2.hSizedBox,
        Wrap(
          children: [
            ...attrData.values!.map(item),
          ],
        ),
      ],
    ).paddingSymmetric(horizontal: 7).alignLeft();
  }

  imgBox(String e) {
    return ZImage.memory(bytes: e.bytes, width: 160, height: 160, fit: BoxFit.fill);
  }

  var imgIndex = 0.obs;

  void onPageChanged(int index) {
    imgIndex.value = index;
  }

  Widget imgIndexBox(int index) {
    return Obx(
      () => ZContainer(
        radius: 8,
        color: index == imgIndex.value ? const Color(0xFF22CE67) : Colors.white60,
        width: 10,
        height: 3,
        margin: const EdgeInsets.symmetric(horizontal: 1),
      ),
    );
  }
}
